package com.heima.wemedia.service.impl;
/*
    
 需求描述：
 @Author: wang
 @Date: 2022/10/13 22:28
 
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmNewsMaterialMapper newsMaterialMapper;


    @Override
    public ResponseResult upload(MultipartFile multipartFile) throws IOException {


        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        String filename = multipartFile.getOriginalFilename();
        assert filename != null;
        filename = UUID.randomUUID().toString() + "." + filename.split("\\.")[1];

        InputStream inputStream = multipartFile.getInputStream();
        String path = fileStorageService.uploadImgFile("", filename, inputStream);

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setType((short) 0);
        wmMaterial.setUrl(path);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);


        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 查询（图片）素材列表
     *
     * @param dto size page isCollection(是否收藏)
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        WmUser user = WmThreadLocalUtil.getUser();
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmMaterial::getUserId, user.getId());
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, 1);
        }
        Page<WmMaterial> page = page(new Page<>(dto.getPage(), dto.getSize()), lambdaQueryWrapper);


        List<WmMaterial> list = page.getRecords();


        return PageResponseResult.okResult(list);

    }


    /**
     * 删除素材图片通过素材ID
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPictureById(Integer id) {
        // 判断素材是否还被引用
        List<WmNewsMaterial> list = newsMaterialMapper.selectList(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (list != null && list.size() > 0) {
            log.info("文件删除失败，素材还在被引用");
            return ResponseResult.errorResult(501,"文件删除失败");
        }

        // 获取url，删除minion数据，再删除素材数据表
        WmMaterial material = getById(id);
        fileStorageService.delete(material.getUrl());
        removeById(id);
        return ResponseResult.okResult(200,"操作成功");
    }


    /**
     * 通过id收藏与取消收藏素材
     * @param id 素材Id
     * @param type  收藏为1，取消为0
     * @return
     */
    @Override
    public ResponseResult cancelCollectOrCollect(Integer id, short type) {
        WmMaterial material = getById(id);
        //参数无效
        if (material==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        material.setId(id);
        material.setIsCollection(type);
        updateById(material);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
